(function() {
	var klp_autopage = $('klp_autopage');
	var nextpageurl = klp_autopage.getAttribute('rel').valueOf();
	var curpage = parseInt(klp_autopage.getAttribute('curpage').valueOf());
	var totalpage = parseInt(klp_autopage.getAttribute('totalpage').valueOf());
	var autopagenum = 0;
	var maxpage = (curpage + autopagenum) > totalpage ? totalpage : (curpage + autopagenum);
	var loadstatus = 0;
	klp_autopage.onclick = function() {
		var oldloadstatus = loadstatus;
		loadstatus = 2;
		klp_autopage.innerHTML = '正在加载, 请稍后...';
		getnextpagecontent();
		loadstatus = oldloadstatus;
	};
	if(autopagenum > 0) {
		window.onscroll = function () {
			var curtop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
			if(curtop + document.documentElement.clientHeight + 500 >= document.documentElement.scrollHeight && !loadstatus) {
				loadstatus = 1;
				klp_autopage.innerHTML = '正在加载, 请稍后...';
				setTimeout(getnextpagecontent, 1000);
			}
		};
	}
	function getnextpagecontent() {
		if(curpage + 1 > totalpage) {
			window.onscroll = null;
			klp_autopage.style.display = 'none';
			return;
		}
		if(loadstatus != 2 && curpage + 1 > maxpage) {
			klp_autopage.innerHTML = '下一页 ?';
			if(curpage + 1 > maxpage) {
				window.onscroll = null;
			}
			return;
		}
		curpage++;
		var url = nextpageurl + '&t=' + parseInt((+new Date()/1000)/(Math.random()*1000));
		var x = new Ajax('HTML');
		x.get(url, function (s) {
			s = s.replace(/\n|\r/g, '');
			if(s.indexOf("id=\"klp_autopage\"") == -1) {
				$("klp_autopage").style.display = "none";
				window.onscroll = null;
			}
				var tableobj = $('mothreadlisttableid');
				var nexts = s.match(/\<li id="mo_normalthread_(\d+)"\>(.+?)\<\/li>/g);
				for(i in nexts) {
					if(i == 'index' || i == 'lastIndex') {
						continue;
					}
					var insertid = nexts[i].match(/<li id="mo_normalthread_(\d+)"\>/);
					if(!$('mo_normalthread_' + insertid[1])) {

						var newbody = document.createElement('li');
						tableobj.appendChild(newbody);
						var div = document.createElement('div');
						div.innerHTML = '<ul>' + nexts[i] + '</ul>';
						tableobj.replaceChild(div.childNodes[0].childNodes[0], tableobj.lastChild);
					}
				}		
			var pageinfo = s.match(/\<span id="klp_page"\>(.+?)\<\/span\>/);
			nextpageurl = nextpageurl.replace(/&page=\d+/, '&page=' + (curpage + 1));
			$('klp_page').innerHTML = pageinfo[1];
			if(curpage + 1 > totalpage) {
				klp_autopage.style.display = 'none';
			} else {
				klp_autopage.innerHTML = '下一页 ?';
			}
			loadstatus = 0;
		});
	}

})();